package com.sae.vote.service;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.sae.vote.entity.Users;
import com.sae.vote.util.DbUtilsTemplate;

/**
 * 用户相关业务
 * 
 */
@Repository
public class UserService {

	@Autowired
	private DbUtilsTemplate dbUtilsTemplate;

	/**
	 * 检查用户名密码
	 * 
	 * @param username
	 * @param password
	 * @return
	 * @throws SQLException
	 */
	public Users checkLogin(String username, String password)
			throws SQLException {
		return dbUtilsTemplate.getReadRunner().query(DbUtilsTemplate.S2,
				new BeanHandler<Users>(Users.class), username, password);
	}

	/**
	 * 
	 * @param user
	 * @throws SQLException
	 */
	public boolean register(Users user) throws SQLException {
		int count = dbUtilsTemplate.getReadRunner().query(DbUtilsTemplate.S12,
				new ResultSetHandler<Integer>() {

					@Override
					public Integer handle(ResultSet rs) throws SQLException {
						while (rs.next()) {
							return rs.getInt(1);
						}
						return 0;
					}
				}, user.getUsername());
		if (count > 0) {
			return false;
		} else {
			dbUtilsTemplate.getWriteRunner().update(DbUtilsTemplate.S13,
					user.getUsername(), user.getPasswd(), user.getGender(),
					user.getEmail(), (byte)1);
			return true;
		}
	}
}
